package com.maicss.coursedesign.servlet;

import com.maicss.coursedesign.dao.UserDao;
import com.maicss.coursedesign.types.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String type = req.getParameter("type");
        if (type == null) {
            resp.sendRedirect("../index.jsp");
        } else if (type.equals("invitationCode")) {
            invitationCodeService(req, resp);
        } else if (type.equals("changePassword")) {
            changePasswordService(req, resp);
        } else if (type.equals("checkLoginStatus")) {
            checkLoginStatusService(req, resp);
        } else if (type.equals("changeUserName")) {
            changeUserNameService(req, resp);
        } else if (type.equals("changeUserHead")) {
            changeUserHeadService(req, resp);
        } else if (type.equals("cancelUser")) {
            cancelUserService(req, resp);
        }
    }

    protected void changeUserHeadService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = (String) req.getSession().getAttribute("user");
        int head = Integer.parseInt(req.getParameter("head")) % 21;
        User user = UserDao.GetUserByName(userName);
        assert user != null;
        boolean res = UserDao.ChangeUserHead(user.getId(), head);
        if (res) {
            resp.getWriter().print(String.format("%d", head));
        } else {
            req.setAttribute("title", "头像修改失败");
            req.setAttribute("context", "头像没有被修改，这可能是服务器错误!");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        }

    }


    protected void checkLoginStatusService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = (String) req.getSession().getAttribute("user");
        if (user != null) {
            if (user.equals("")) {
                resp.getWriter().print("false");
            } else {
                resp.getWriter().print("true");
            }
        } else {
            resp.getWriter().print("false");
        }
    }

    protected void changeUserNameService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldName = (String) req.getSession().getAttribute("user");
        String newName = req.getParameter("newName");
        req.setAttribute("title", "用户名修改失败");
        if (newName.length() == 0) {
            req.setAttribute("context", "新用户名不能为空，请重新检查您的输入!");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        User user = UserDao.GetUserByName(oldName);
        if (user == null) {
            req.setAttribute("context", "您的登录已经失效，请退出后重新登录。");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        boolean res = user.setName(newName);
        if (res) {
            req.setAttribute("title", "用户名修改成功");
            req.setAttribute("context", "用户名已经被成功修改，请您重新登录。");
            req.setAttribute("relogin", "true");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        } else {
            req.setAttribute("context", "服务器错误，您的用户名没有被修改。");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        }
    }

    protected void changePasswordService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = (String) req.getSession().getAttribute("user");
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        req.setAttribute("title", "密码修改失败");
        if (newPassword.length() == 0) {
            req.setAttribute("context", "您的新密码不能为空，请重新检查您的输入!");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        User user = UserDao.GetUserByName(userName);
        if (user == null) {
            req.setAttribute("context", "您的登录已经失效，请退出后重新登录。");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        if (!user.getPassword().equals(oldPassword)) {
            req.setAttribute("context", "您的旧密码不正确，请重新检查后输入。若您已经忘记，请联系系统管理员重置密码。");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        boolean res = user.setPassword(newPassword);
        if (res) {
            req.setAttribute("title", "密码修改成功");
            req.setAttribute("context", "密码已经被成功修改，请您重新登录。");
            req.setAttribute("relogin", "true");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        } else {
            req.setAttribute("context", "服务器错误，您的密码没有被修改。");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        }
    }

    /**
     * 获取用户的邀请码
     * 该Service将在Session中获取UserName，通过该名称获取ID，进而获取验证码，若失败则弹出异常。
     */
    protected void invitationCodeService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = (String) req.getSession().getAttribute("user");
        if (userName == null) {
            return;
        }
        User user = UserDao.GetUserByName(userName);
        try {
            assert user != null;
            String code = UserDao.CreateInvitationCode(user.getId());
            resp.getWriter().print(code);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取用户输入的密码
     * 该Service将在Session中获取cancelName，通过该名称获取该对象，进而获取密码。
     * 判断输入密码和用户密码是否一致，若不一致则弹出异常。
     */
    protected void cancelUserService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("password");
        String name = (String) req.getSession().getAttribute("user");
        User user = UserDao.GetUserByName(name);
        req.setAttribute("title","用户注销失败！");
        if (user == null) {
            req.setAttribute("context", "您的登录已经失效，请退出后重新登录。");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        String userPassword = user.getPassword();
        if(!password.equals(userPassword)){
            req.setAttribute("context", "密码错误，用户注销失败！");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
            return;
        }
        boolean b = UserDao.deleteUser(name);
        if (b) {
            req.setAttribute("title","用户注销成功！");
            req.setAttribute("context", "用户注销成功，请您重新登录或注册！");
            req.setAttribute("relogin", "true");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        }else{
            req.setAttribute("context", "密码错误，用户注销失败！");
            req.getRequestDispatcher("pages/message.jsp").forward(req, resp);
        }
    }

}
